/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-11-12 下午12:31:46
 */
package com.absir.appserv.system.asset;

import com.absir.appserv.system.bean.JPayTrade;
import com.absir.appserv.system.bean.value.JePayStatus;
import com.absir.appserv.system.helper.HelperJson;
import com.absir.appserv.system.service.BeanService;
import com.absir.appserv.system.service.utils.PayUtils;
import com.absir.server.in.Input;
import com.absir.server.value.Body;
import com.absir.server.value.Param;
import com.absir.server.value.Server;
import com.alipay.sign.Signature;
import com.alipay.util.AlipayNotify;

/**
 * @author absir
 * 
 */
@Server
public class Asset_alipay extends AssetServer {

	/**
	 * @param tradeNo
	 * @param outTradeNo
	 * @param tradeStatus
	 * @param total_fee
	 * @param input
	 * @return
	 */
	@Body
	public String notify(@Param String trade_no, @Param String out_trade_no, @Param String trade_status, @Param float total_fee,
			Input input) {
		if (AlipayNotify.verify(HelperJson.buildParams(input.getParamMap()), Signature.RSA)) {
			JPayTrade payTrade = BeanService.ME.get(JPayTrade.class, out_trade_no);
			if (payTrade != null) {
				if (!trade_status.equals("WAIT_BUYER_PAY") && !trade_status.equals("TRADE_FINISHED")) {
					if (trade_status.equals("TRADE_SUCCESS")) {
						if (payTrade.getStatus() == null) {
							payTrade.setTradeNo(trade_no);
							payTrade.setStatus(total_fee >= payTrade.getAmount() ? JePayStatus.PAYED : JePayStatus.ERROR);
							PayUtils.proccessDone(payTrade);
						}

					} else {
						payTrade.setStatus(JePayStatus.ERROR);
					}

					payTrade.setStatusData(trade_status);
					BeanService.ME.merge(payTrade);
				}

				return "success";
			}
		}

		return "fail";
	}
}
